﻿using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using Microsoft.AspNetCore.SignalR;
using ReturnValue;
using SignalRBackend;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class AddMaterialAskHander : IRequestHandler<AddMaterialAskCommand, ApiResult<int>>
    {
        private readonly IRepository<MaterialAskModel> materialAskRepo;
        private readonly IMapper mapper;
        private readonly IHubContext<MessageHub> hubContext;

        public AddMaterialAskHander(
            IRepository<MaterialAskModel> materialAskRepo, 
            IMapper mapper,
            IHubContext<MessageHub> hubContext)
        {
            this.materialAskRepo = materialAskRepo;
            this.mapper = mapper;
            this.hubContext = hubContext;
        }

        /// <summary>
        /// 所需物料申请单处理程序
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(AddMaterialAskCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            
            //物料申请编码不能重复
            var exists = materialAskRepo.GetAll().Where(a => a.MaterialAskCode == request.MaterialAskCode).FirstOrDefault();
            if (exists != null)
            {
                result.Code = StatusCode.Fail;
                result.Message = "该物料申请编码已存在，请重新输入！";
                return await Task.FromResult(result);
            }
            
            var model = mapper.Map<MaterialAskModel>(request);
            model.Id = YitIdHelper.NextId();
            model.CreateTime = DateTime.Now;
            model.IsDel = false;
            
            if (model != null)
            {
                // 添加物料申请单
                await materialAskRepo.AddAsync(model);
                
                // 发送待办通知
                await SendNotification(model, cancellationToken);
                
                result.Code = StatusCode.Success;
                result.Message = "添加成功！";
                return await Task.FromResult(result);
            }
            else
            {
                result.Code = StatusCode.Fail;
                result.Message = "添加失败！";
                return await Task.FromResult(result);
            }
        }
        
        /// <summary>
        /// 发送物料申请待办通知
        /// </summary>
        /// <param name="materialAsk">物料申请单</param>
        /// <param name="cancellationToken">取消令牌</param>
        private async Task SendNotification(MaterialAskModel materialAsk, CancellationToken cancellationToken)
        {
            try
            {
                // 获取待办数量
                int pendingCount = materialAskRepo.GetAll()
                    .Count(m => m.MaterialAskStatus == "进行中" && m.IsDel == false);
                
                // 发送通知消息
                await hubContext.Clients.All.SendAsync("ReceiveMaterialAskNotification", 
                    materialAsk.MaterialAskCode, 
                    $"您有一条待处理物料申请单", 
                    cancellationToken);
                
                // 更新待办数量
                await hubContext.Clients.All.SendAsync("UpdatePendingCount", 
                    pendingCount,
                    cancellationToken);
            }
            catch (Exception ex)
            {
                // 记录异常，但不影响主流程
                Console.WriteLine($"发送通知失败: {ex.Message}");
            }
        }
    }
}